package com.doradance.account.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.account.utils.FragmentUtils;
import com.doradance.app.MainActivity;
import com.doradance.app.appactivity.AddBabyActivity;
import com.doradance.app.appactivity.SelectBabyActivity;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.common.http.TokenInfo;
import com.doradance.entity.WexinBean;
import com.doradance.entity.YzEntity;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.GsonUtils;
import com.pachong.android.frameworkbase.utils.RegularUtils;
import com.pachong.android.frameworkbase.utils.io.SharePreferenceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.doradance.account.AccountManager.getTokenInfo;

public class LoginPhoneActivity extends BaseActivity {
    String optimize;
    @Bind(R.id.et_login_phone)
    EditText mEtLoginPhone;
    @Bind(R.id.et_login_code)
    EditText mEtLoginCode;
    @Bind(R.id.iv_login_delete)
    ImageView mIvLoginDelete;
    @Bind(R.id.btn_get_login_code)
    Button mBtnGetLoginCode;
    private MyCountDownTimer mc;
    public final static int LOGINADD=2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolsBar();
        initChangeEt();
    }

    private void initChangeEt() {
        mEtLoginPhone.setFocusable(true);
        mEtLoginPhone.setInputType(EditorInfo.TYPE_CLASS_PHONE);//设置数字键盘显示
        mEtLoginCode.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        mEtLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() != 0) {
                    mIvLoginDelete.setVisibility(View.VISIBLE);
                } else {
                    mIvLoginDelete.setVisibility(View.INVISIBLE);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initToolsBar() {
        setTitle(getString(R.string.login));
        getCustomToolbar().addLeftImageButton(R.mipmap.back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, LoginPhoneActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_login_phone, null);
    }

    @OnClick({R.id.iv_login_delete, R.id.btn_get_login_code, R.id.btn_login_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_login_delete:
                mEtLoginPhone.setText("");
                mIvLoginDelete.setVisibility(View.INVISIBLE);
                break;
            case R.id.btn_get_login_code:
                getCode();
                break;
            case R.id.btn_login_confirm:
                login();
                break;
        }
    }

    private void login() {
        if (TextUtils.isEmpty(getLoginName())) {
            FragmentUtils.showWarnDialog("请输入手机号码", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getLoginName())) {
            FragmentUtils.showWarnDialog("请输入正确的手机号码", getSupportFragmentManager());
            return;
        } else if(TextUtils.isEmpty(getCapth())){
            FragmentUtils.showWarnDialog("请输入验证码", getSupportFragmentManager());
            return;
        }
        yzCode(getLoginName(),getCapth());
    }

    private void yzCode(final String phone,final String capth) {
        MyHttpRequest request = new MyHttpRequest(this);
        String capthUrl= String.format(UrlCenter.YZCODE,1,phone,capth);
        Log.e("1111",capthUrl);
        request.get(capthUrl, null, new DataRequestListener<YzEntity>(YzEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(YzEntity o) {
                super.onSuccess(o);
                if(o.isValue()==true){
                    Login(phone,capth);
                }else{
                    EasyToast.showToast(getApplicationContext(),"验证码错误");
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getApplicationContext(),strMsg);
            }
        });

    }
    //登录
    private void Login(String phone,String capth) {
        MyHttpRequest request = new MyHttpRequest(this);
        JSONObject job = new JSONObject();
        try {
            job.put("phone",phone);
            job.put("captcha",capth);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.post(UrlCenter.LOGIN, job, new DataRequestListener<String>(String.class) {

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                try {
                    JSONObject jsonObject = new JSONObject(o);
                    optimize = jsonObject.getString("optimize");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                WexinBean wexinBean = GsonUtils.string2Object(o, WexinBean.class);
                WexinBean.TokenBean token = wexinBean.getToken();
                TokenInfo tokenInfo = getTokenInfo();
                tokenInfo.setAccessToken(token.getAccess_token());
                tokenInfo.setExpiresAt(token.getExpires_at());
                tokenInfo.setMacKey(token.getMac_key());
                tokenInfo.setRefreshToken(token.getRefresh_token());
                tokenInfo.setServerTime(token.getServer_time());
                tokenInfo.setUser_id(token.getUser_id());
                SharePreferenceUtil.saveString(getApplicationContext(),"isOptimize","isOptimize",optimize);
                if(tokenInfo!=null && optimize.equals("false")){
                    AddBabyActivity.start(LoginPhoneActivity.this,LOGINADD);
                }else{
                    SelectBabyActivity.start(LoginPhoneActivity.this);
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });

    }

    private void getCode() {
        if (TextUtils.isEmpty(getLoginName())) {
            FragmentUtils.showWarnDialog("请输入手机号码", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getLoginName())) {
            FragmentUtils.showWarnDialog("请输入正确的手机号码", getSupportFragmentManager());
            return;
        }
        setGetCodeRequest(getLoginName());
    }

    private void setGetCodeRequest(String loginName) {
        MyHttpRequest request = new MyHttpRequest(this);
        String urlCode = String.format(UrlCenter.CODE,1,loginName);
        UrlParams urlParams = new UrlParams();
        urlParams.put("type",1+"");
        urlParams.put("phone",loginName);
        request.post(urlCode, urlParams, new DataRequestListener<String>(String.class
        ) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String str) {
                super.onSuccess(str);
                        mc = new MyCountDownTimer(90000, 1000);
                        mc.start();
                        EasyToast.showToast(LoginPhoneActivity.this, "发送验证码成功");
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(LoginPhoneActivity.this, strMsg);
            }
        });

    }

    private String getLoginName() {
        return mEtLoginPhone.getText().toString().trim();
    }
    private String getCapth() {
        return mEtLoginCode.getText().toString().trim();
    }

    /**
     * 继承 CountDownTimer 防范
     *
     * 重写 父类的方法 onTick() 、 onFinish()
     */
    class MyCountDownTimer extends CountDownTimer {
        /**
         *
         * @param millisInFuture
         *      表示以毫秒为单位 倒计时的总数
         *
         *      例如 millisInFuture=1000 表示1秒
         *
         * @param countDownInterval
         *      表示 间隔 多少微秒 调用一次 onTick 方法
         *
         *      例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         *
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mBtnGetLoginCode.setText("重新获取");
            mBtnGetLoginCode.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Log.i("MainActivity", millisUntilFinished + "");
            if(mBtnGetLoginCode!=null){
                mBtnGetLoginCode.setClickable(false);
                mBtnGetLoginCode.setText( millisUntilFinished / 1000 +"s");
            }

        }
    }
}
